<template>
  <view class="user-avatar-container">
    <image 
      :src="avatarUrl" 
      :class="['user-avatar', sizeClass]"
      mode="aspectFill"
      @error="onImageError"
      @load="onImageLoad"
    />
    <view v-if="showLoadingMask && isLoading" class="loading-mask">
      <text>加载中...</text>
    </view>
  </view>
</template>

<script>
import { getAvatarUrl, isAvatarValid } from '@/utils/avatarUtils'

export default {
  name: 'UserAvatar',
  props: {
    // 头像数据，可能是JSON字符串或URL字符串
    avatar: {
      type: [String, Object],
      default: null
    },
    // 尺寸：small, medium, large
    size: {
      type: String,
      default: 'medium'
    },
    // 是否显示加载遮罩
    showLoadingMask: {
      type: Boolean,
      default: false
    },
    // 默认头像路径
    defaultAvatar: {
      type: String,
      default: '/static/images/default-avatar.png'
    }
  },
  
  data() {
    return {
      isLoading: true,
      hasError: false
    }
  },
  
  computed: {
    avatarUrl() {
      const url = getAvatarUrl(this.avatar, this.defaultAvatar)
      console.log('UserAvatar组件: 头像URL解析结果:', url, '原始数据:', this.avatar)
      return url
    },
    
    sizeClass() {
      return `size-${this.size}`
    },
    
    isValidAvatar() {
      return isAvatarValid(this.avatar)
    }
  },
  
  methods: {
    onImageLoad() {
      console.log('UserAvatar组件: 头像加载成功')
      this.isLoading = false
      this.hasError = false
      this.$emit('load')
    },
    
    onImageError(e) {
      console.error('UserAvatar组件: 头像加载失败:', e)
      this.isLoading = false
      this.hasError = true
      this.$emit('error', e)
    }
  }
}
</script>

<style lang="scss" scoped>
.user-avatar-container {
  position: relative;
  display: inline-block;
}

.user-avatar {
  border-radius: 50%;
  object-fit: cover;
  background-color: #f0f0f0;
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  &.size-small {
    width: 32px;
    height: 32px;
  }
  
  &.size-medium {
    width: 50px;
    height: 50px;
  }
  
  &.size-large {
    width: 80px;
    height: 80px;
  }
}

.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  
  text {
    color: #fff;
    font-size: 12px;
  }
}
</style>
